#!/bin/bash

fresh_install=false

data_dir=/var/named

if [ ! -d ${data_dir} ]; then
	UUID=$(mdata-get sdc:uuid)
	DDS=zones/${UUID}/data

	if zfs list ${DDS} 1>/dev/null 2>&1; then
		zfs create ${DDS}/named || true

		zfs set mountpoint=${data_dir} ${DDS}/named

		# znapzend for backup
		znapzendzetup create --recursive --tsformat='%Y-%m-%d-%H%M%S' --donotask \
			SRC '7day=>8hour,30day=>1day,1year=>1week,10year=>1month' ${DDS}
		/usr/sbin/svcadm enable svc:/pkgsrc/znapzend:default
	else
		mkdir -p ${data_dir}
	fi
fi

chown -R 922:922 ${data_dir}

conf_dir=/opt/local/etc/named
if [[ ! -e /opt/local/etc/named.conf ]]; then
	cp /opt/local/share/examples/bind9/named.conf /opt/local/etc/
    chown 922:922 /opt/local/etc/named.conf
	fresh_install=true
fi

if [[ ! -d ${conf_dir} ]]; then
	mkdir ${conf_dir}
    chown 922:922 ${conf_dir}
fi
if [[ ! -e ${conf_dir}/bind.keys ]]; then
	cp /opt/local/share/examples/bind9/bind.keys ${conf_dir}/bind.keys
	cp -r /opt/local/share/examples/bind9/config/* ${conf_dir}/
    chown -R 922:922 ${conf_dir}
fi

if [ ${fresh_install} == true ];then
	if /usr/sbin/mdata-get allow_recursion 1>/dev/null 2>&1; then
		ACL=$(/usr/sbin/mdata-get allow_recursion)
		gsed -i "s|allow-recursion { 127.0.0.1; };|allow-recursion { ${ACL}; };|" /opt/local/etc/named/named.conf.options 1>/dev/null 2>&1    
	fi

	if /usr/sbin/mdata-get allow_query 1>/dev/null 2>&1; then
		ACL=$(/usr/sbin/mdata-get allow_query)
		gsed -i "s|allow-query { 127.0.0.1; };|allow-query { ${ACL}; };|" /opt/local/etc/named/named.conf.options 1>/dev/null 2>&1    
	fi
fi